import {createRouter, createWebHashHistory, onBeforeRouteUpdate} from "vue-router";
import Register from "@/views/Register.vue";
import IndexVue from "@/views/menu/IndexVue.vue";
import {ElMessage} from "element-plus";
import {useUserStore} from "@/store/user.js";

const routes = [
	{
		path: '/register',
		name: 'register',
		component: Register
	},
	{
		path: '/',
		name: 'index',
		component: () => import('@/views/Index.vue'),
		children: [
			{
				path: '/',
				name: 'index',
				component: IndexVue
			},
			{
				path: '/user/index',
				component: () => import('@/views/menu/User.vue')
			},
			{
				path: '/role/index',
				component: () => import('@/views/menu/Role.vue')
			},
			{
				path: '/menu/index',
				component: () => import('@/views/menu/Menu.vue')
			},
			{
				path: '/goods/index',
				component: () => import('@/views/menu/Goods.vue')
			},
			{
				path: '/sys/order/index',
				component: () => import('@/views/menu/Order.vue')
			}
		]
	},
	{
		path: '/login',
		name: 'login',
		component: () => import('@/views/Login.vue'),
	}
]

const router = createRouter({
	history: createWebHashHistory(),
	routes
})

const user = JSON.parse(sessionStorage.getItem('user'))
const token = user ? user.token : undefined
router.beforeResolve((to, from, next) => {
	// const user = JSON.parse(sessionStorage.getItem('user'))
	// const token = user ? user.token : undefined
	const userStore = useUserStore()
	if (to.path !== '/login' && !userStore.token) {
		ElMessage.error("请先登录")
		next('/login')
	}
	next()
})

export default router